/**
 * 
 */
package com.orisper.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import aos.framework.core.id.AOSId;
import aos.framework.core.utils.AOSCfgHandler;
import aos.framework.core.utils.AOSUtils;

/**
 * @author Administrator
 *
 */
public class UploadUtils {

	private static boolean saveToLocal(MultipartFile file, String absPath) {
		if (!file.isEmpty()) {
			File localFile = new File(absPath);
			try {
				file.transferTo(localFile);
			} catch (IllegalStateException e) {
				return false;
			} catch (IOException e) {
				return false;
			}
			return true;
		}
		return false;
	}

	public static String save(MultipartFile file, String virtualDir) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String dateStr = sdf.format(new Date());
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String virtualDirPath = String.format(virtualDir + "/%s", dateStr);

		String saveRootPath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
		if (AOSUtils.isNotEmpty(AOSCfgHandler.getValue("picture_path"))){
			saveRootPath = AOSCfgHandler.getValue("picture_path");
		}
		String absDirPath = saveRootPath + virtualDirPath;
		absDirPath = absDirPath.replaceAll("\\/", "/");
		absDirPath = absDirPath.replaceAll("\\\\", "/");
		absDirPath = absDirPath.replaceAll("//", "/");
		File dir = new File(absDirPath);
		if (!dir.exists())
			dir.mkdirs();
		String newFileName = AOSId.uuid() + suffix;
		String absPath = absDirPath + "/" + newFileName;
		String virtualPath = virtualDirPath + "/" + newFileName;
		saveToLocal(file, absPath);
		return virtualPath;
	}

}
